package com.zHan.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zHan.controller.utils.CodeEnum;
import com.zHan.controller.utils.R;
import com.zHan.pojo.Book;
import com.zHan.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService bookService;

    @PostMapping
    public R save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        int code=flag? CodeEnum.SAVE_OK.code():CodeEnum.SAVE_ERR.code();
        String msg = flag? CodeEnum.SAVE_OK.msg():CodeEnum.SAVE_ERR.msg();
        return new R(flag,code,msg);
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        int code=flag? CodeEnum.DELETE_OK.code():CodeEnum.DELETE_ERR.code();
        String msg = flag? CodeEnum.DELETE_OK.msg():CodeEnum.DELETE_ERR.msg();
        return new R(flag,code,msg);
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        int code=flag? CodeEnum.UPDATE_OK.code():CodeEnum.UPDATE_ERR.code();
        String msg = flag? CodeEnum.UPDATE_OK.msg():CodeEnum.UPDATE_ERR.msg();
        return new R(flag,code,msg);
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        int code = book != null ? CodeEnum.GET_OK.code() : CodeEnum.GET_ERR.code();
        String msg = book != null ? "":CodeEnum.GET_ERR.msg();
        return new R(book,code,msg);
    }

    @GetMapping
    public R getAll() {
        List<Book> bookList = bookService.getAll();
        int code = bookList != null ? CodeEnum.GET_OK.code() : CodeEnum.GET_ERR.code();
        String msg = bookList != null ? "":CodeEnum.GET_ERR.msg();
        return new R(bookList,code,msg);
    }

    @GetMapping("/{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize,Book book) {
        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        if (currentPage>page.getPages()){
            page = bookService.getPage((int) page.getPages(), pageSize,book);
        }
        int code = page != null ? CodeEnum.GET_OK.code() : CodeEnum.GET_ERR.code();
        String msg = page != null ? "":CodeEnum.GET_ERR.msg();
        return new R(page,code,msg);
    }
}
